处理系统调用中的错误

每个系统调用都应该有出错的处理, 这是很有必要的, 因为系统调用会修改一些重要的系统配置文件, 如果这些文件遭到破坏, 那系统就会遇到麻烦.

如果 open无法打开指定的文件, 它会返回 -1. 同样地, 当 read无法读的是偶, 它也会返回 -1. -1 是表示在系统调用中除了些问题, 调用者每次都必须检查返回值, 一旦检测到错误, 必须做出相应的处理

确定错误种类: errno

内核通过全局变量 errno 来知名错误的类型, 每个程序都可以访问到这个变量.

error(3) 的连接帮助和 <errno.h> 中包含错误代码和相应的说明, 以下是一些例子:

#define     EPERM   1       /* Operation not permitted */
#define     ENOENT  2       /* No suck file or directory */
#define     ESRCH   3       /* No suck process */
#define     EINTR   4       /* Interupted system call */
#deinf      EIO     5       /* I/O error */

不同错误需要不同的处理

根据以上累出的错误类型, 在程序中进行相应的处理

#include <errno.h>

extern int errno;

int sample()
{
    int fd;
    fd = open("file", O_RDONLY);
    if (fd == -1)
    {
        printf("Cannot open file: ");
        if (errno == ENOENT)
            printf("There is no suck file.");
        else if (errno == EINTR)
            printf("Interrupted while open file.");
        else if (errno == EACCESS)
            printf("You do not have permission to open file.");
        ...
    }
}

显示错误信息: perror(3)

另外一种更简单的方法根据错误代码答应相应的字符串是用 perror(string) 找个函数, 它会自己查找错误代码, 在标准错误输出中显示出相应的错误信息.

sample()
{   
    int fd;
    fd = open("file", O_RDONLY);
    if (fd == -1)
    {
        perror("Cannot open file");
        return;
    }
}